﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Serilog;
using System.IO;

namespace Common
{
  class ConfigHelper
  {
    public static T GetConfigFromFile<T>(string fileName, string ext = "json") where T : class
    {
      try
      {
        var json = GetContentFromFile(fileName, ext);
        var result = JsonConvert.DeserializeObject<T>(json);
        return result;
      }
      catch (Exception ex)
      {
        Log.Warning("GetConfigFromFile：" + fileName + "\t" + ex.Message);
        return default;
      }
    }

    public static string GetContentFromFile(string fileName, string ext)
    {
      string configFile = GetConfigFileName(fileName, ext);
      if (!File.Exists(configFile)) return string.Empty;
      var jsonStr = File.ReadAllText(configFile);
      return jsonStr;
    }

    private static string GetConfigFileName(string fileName, string ext)
    {
      string configFileName = string.Format("{0}.{1}", fileName, ext);
      return Path.Combine("Config", configFileName);
    }
  }
}
